package com.shuaiche.yeguan.rn;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.geetest.onelogin.OneLoginHelper;
import com.shuaiche.yeguan.MainActivity;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.SCApplication;
import com.shuaiche.yeguan.audio.AudioRecordManager;
import com.shuaiche.yeguan.audio.AudioRecordStatus;
import com.shuaiche.yeguan.audio.RecordConfig;
import com.shuaiche.yeguan.audio.listener.RecordResultListener;
import com.shuaiche.yeguan.audio.listener.RecordStateListener;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.config.SCUserInfoConfig;
import com.shuaiche.yeguan.model.SCAccessAuthResponse;
import com.shuaiche.yeguan.model.SCCarPicsModel;
import com.shuaiche.yeguan.model.SCUserInfoResponse;
import com.shuaiche.yeguan.model.ShareObj;
import com.shuaiche.yeguan.net.http.DownloadListener;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.net.http.ProgressListener;
import com.shuaiche.yeguan.net.oss.MultiImagesUploadManager;
import com.shuaiche.yeguan.ui.common.PdfPreviewActivity;
import com.shuaiche.yeguan.ui.contract.UploadContractActivity;
import com.shuaiche.yeguan.ui.login.SCLoginWrapHelper;
import com.shuaiche.yeguan.ui.map.ChooseAddressMapActivity;
import com.shuaiche.yeguan.ui.map.LocationMapActivity;
import com.shuaiche.yeguan.ui.report.SCMaintenanceReportActivity;
import com.shuaiche.yeguan.ui.report.UploadDetectionActivity;
import com.shuaiche.yeguan.ui.select.SCPurchaserSelectActivity;
import com.shuaiche.yeguan.ui.select.SelectBrandsActivity;
import com.shuaiche.yeguan.ui.setting.PermissionSettingActivity;
import com.shuaiche.yeguan.ui.share.MultiShareSelectActivity;
import com.shuaiche.yeguan.ui.upload.UploadCarPic;
import com.shuaiche.yeguan.util.DialogUtil;
import com.shuaiche.yeguan.util.SCSavePictureListener;
import com.shuaiche.yeguan.util.SCSavePictureUtils;
import com.shuaiche.yeguan.util.SPUtils;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.views.dialog.PermissionDialog;
import com.shuaiche.yeguan.views.photopicker.intent.PhotoPreviewIntent;
import com.shuaiche.yeguan.views.qrphoto.qr.QrActivity;
import com.tencent.wework.api.IWWAPIEventHandler;
import com.tencent.wework.api.model.BaseMessage;
import com.tencent.wework.api.model.WWMediaLink;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;


public class AndroidModule extends ReactContextBaseJavaModule implements ActivityEventListener {
    private Activity activity;

    public AndroidModule(ReactApplicationContext reactContext) {

        super(reactContext);
    }


    //返回模块名字，方便在RN中引用
    @Override
    public String getName() {
        return "AndroidModule";
    }

    //这两方法是ActivityEventListener接口中的，方便处理一些由此模块跳转后返回的回调事件
    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void onNewIntent(Intent intent) {

    }

    @ReactMethod
    private void finish() {
        try {
            if (getCurrentActivity() != null) {
                getCurrentActivity().finish();
            }
        } catch (Exception e) {

        }
    }

    @ReactMethod
    public void exitApp(){
        try {
            System.exit(0);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @ReactMethod
    private void gotoLogin(ReadableMap params){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }
        SCLoginWrapHelper.starLogintActivity(activity);
    }

    @ReactMethod
    private void updateUserInfo(ReadableMap params){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }
        SCUserInfoResponse userInfoResponse = SCUserInfoConfig.getUserinfo();
        if (params.hasKey("face")){
            userInfoResponse.setFace(params.getString("face"));
        }

        if (params.hasKey("fullname")){
            userInfoResponse.setFullname(params.getString("fullname"));
        }

        if (params.hasKey("perms")){
            userInfoResponse.setPerms(params.getString("perms"));
        }

        SCUserInfoConfig.saveUserinfo(userInfoResponse);

    }

    @ReactMethod
    private void downloadPictures(ReadableMap params){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }
        if (params.hasKey("imgList") && params.getArray("imgList") != null){
            
            List<String> pics = new ArrayList<>();
            ArrayList<Object> temp = params.getArray("imgList").toArrayList();
            for (Object value: temp) {
                pics.add((String) value);
            }
            SCSavePictureUtils.getInstance().saveImage(activity, pics, null,
                    new SCSavePictureListener() {
                        @Override
                        public void onFinish() {
                            ToastShowUtils.showSuccessToast("图片已保存");
                        }
                    });
        }

        
    }

    @ReactMethod
    public void downloadContract(ReadableMap msg){
        activity = getCurrentActivity();
        if (activity == null) {
            return;
        }

        String downloadUrl = msg.getString("downloadUrl");
        String fileName = msg.getString("fileName");
        boolean isShare = msg.getBoolean("isShare");

        if (isShare){
//            SCDownLoadUtils.downLoadAndShare(activity,fileName,downloadUrl);
            downloadContract(fileName,downloadUrl);
        }else {

        }
    }

    private void downloadContract(String fileName,String downloadUrl) {


        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        HttpHelper.getInstance().url(downloadUrl)
                .addDownLoadListener(new DownloadListener() {
                    @Override
                    public void onDownloadSuccess(String path, long total) {
                        File downloadFile = new File(path);
                        if (downloadFile != null && downloadFile.length() == total) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);

                                    Uri fileUri = FileProvider.getUriForFile(activity, "com.shuaiche.yeguan.fileprovider", file);

                                    Intent shareIntent = new Intent();
                                    shareIntent.setAction(Intent.ACTION_SEND);
                                    shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
                                    shareIntent.setType("text/plain");
                                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                                    activity.startActivity(Intent.createChooser(shareIntent, "分享文件"));
                                }
                            });

                        } else {
                            downloadFile.delete();
                        }

                    }

                    @Override
                    public void onDownloadSuccess(String path) {

                    }

                    @Override
                    public void onDownloading(int progress) {

                    }

                    @Override
                    public void onDownloadFailed() {

                    }
                })
                .addProgressListener(new ProgressListener() {
                    @Override
                    public void onProgress(long currentBytes, long contentLength, boolean done) {

                    }
                })
                .addFileName(fileName)
                .addSavePath(file.getAbsolutePath() + "/").downloadFile();
    }

    @ReactMethod
    private void previewImages(ReadableMap params){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        ArrayList<String> selectUrls = new ArrayList<>();

        if (params.hasKey("picList")){
            ReadableArray array = params.getArray("picList");
            for (int i = 0; i < array.size(); i++) {
                selectUrls.add(array.getString(i));

            }
        }

        int index = 0;
        if (params.hasKey("index")){
            index = params.getInt("index");
        }

        PhotoPreviewIntent intent = new PhotoPreviewIntent(activity);
        intent.setCurrentItem(index);
        intent.setPhotoPaths(selectUrls);
        intent.setShowMainPic(false);
        intent.setShowDelete(false);
        activity.startActivity(intent);
    }

    @ReactMethod
    private void sharePlatFormCarListImages(ReadableMap params){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        List<String> selectUrls = new ArrayList<>();
        List<Long> carIds = new ArrayList<>();

        if (params.hasKey("selectCars")){
            ReadableArray array = params.getArray("selectCars");
            for (int i = 0; i < array.size(); i++) {
                double carId = array.getMap(i).getDouble("carId");
                String mainPic = array.getMap(i).getString("mainPic");
                selectUrls.add(mainPic);

                String temporary = String.valueOf(carId);
                BigDecimal bigDecimal = new BigDecimal(temporary);
                String result = bigDecimal.toPlainString();
                carIds.add(Long.parseLong(result));
            }
        }

        StringBuffer address = new StringBuffer();
        if (params.hasKey("companyInfo")){
            ReadableMap maps = params.getMap("companyInfo");
            if (maps.hasKey("provinceName")){
                address.append(maps.getString("provinceName"));
            }
            if (maps.hasKey("cityName")){
                address.append(maps.getString("cityName"));
            }
            if (maps.hasKey("districtName")){
                address.append(maps.getString("districtName"));
            }
            if (maps.hasKey("address")){
                address.append(maps.getString("address"));
            }
        }

        JSONObject paramsJson = new JSONObject();
        paramsJson.put("carIds", carIds);
        paramsJson.put("userId", SCUserInfoConfig.getUserinfo().getUserId());
        paramsJson.put("merchantId", SCUserInfoConfig.getUserinfo().getMerchantId());
//        paramsJson.put("picUnionId",picUnionId);
        final String paramsString = paramsJson.toJSONString();
        final String shareUrl = SCAppConfig.H5_CAR_LIST;
        String content = "【诚信车商】" + SCUserInfoConfig.getUserinfo().getMerchantName() +
                "\r\n【联系方式】" + SCUserInfoConfig.getUserinfo().getUsername() + SCUserInfoConfig.getUserinfo().getFullname() +
                "\r\n【联系地址】"+address.toString();
//        if (SCUserInfoConfig.getCompanyInfo() != null) {
//            content = content + SCUserInfoConfig.getCompanyInfo().getDetailAddress();
//        }

        Bundle bundle = new Bundle();
        ShareObj shareObj = new ShareObj.ShareObjBuilder("", "", shareUrl)
                .picUrls(selectUrls)
                .multiContent(content)
                .bizType("carList")
                .dataMerchantId(SCUserInfoConfig.getUserinfo().getMerchantId())
                .paramsJson(paramsJson)
                .build();
        bundle.putSerializable("shareObj", shareObj);

        Intent intent = new Intent(activity, MultiShareSelectActivity.class);

        intent.putExtras(bundle);

        activity.startActivity(intent);

    }

    @ReactMethod
    private void goToPermission(){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        activity.startActivity(new Intent(activity, PermissionSettingActivity.class));

    }

    @ReactMethod
    public void logOffSuccess() {
        try {
            activity = getCurrentActivity();

            if (activity == null) {
                return;
            }
            OneLoginHelper.with().register(SCAppConfig.APP_ID_OL);

            SCUserInfoConfig.deteleUserInfo();
            SCUserInfoConfig.deteleCompanyInfo();
            SCUserInfoConfig.deleteMessageInfo();
            SCLoginWrapHelper.starLogintActivity(activity);
            activity.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ReactMethod
    public void sessionExpired() {
        try {
            activity = getCurrentActivity();

            if (activity == null) {
                return;
            }
            OneLoginHelper.with().register(SCAppConfig.APP_ID_OL);

            SCUserInfoConfig.deteleUserInfo();
            SCUserInfoConfig.deteleCompanyInfo();
            SCUserInfoConfig.deleteMessageInfo();
            SCLoginWrapHelper.starLogintActivity(activity);
            activity.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ReactMethod
    public void logout() {
        try {
            activity = getCurrentActivity();

            if (activity == null) {
                return;
            }
            OneLoginHelper.with().register(SCAppConfig.APP_ID_OL);

            SCUserInfoConfig.deteleUserInfo();
            SCUserInfoConfig.deteleCompanyInfo();
            SCUserInfoConfig.deleteMessageInfo();
            SCLoginWrapHelper.starLogintActivity(activity);
            activity.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ReactMethod
    private void switchApi(ReadableMap params){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }
        if (params.hasKey("switchType")){

           int switchType = params.getInt("switchType");

            SPUtils.saveInt(activity,SPUtils.API_TYPE,switchType);

            ToastShowUtils.showSuccessToast("即将退出,请重新打开APP");

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    System.exit(0);
                }
            }, 1500);
        }
    }


    @ReactMethod
    private void selectMap(ReadableMap params, Callback callback){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }
        double lat = 0;
        double lon = 0;
        if (params.hasKey("lat")){
            lat = params.getDouble("lat");
        }
        if (params.hasKey("lon")){
            lon = params.getDouble("lon");
        }

        Intent intent = new Intent(activity, LocationMapActivity.class);
        intent.putExtra("lat",lat);
        intent.putExtra("lon",lon);
        activity.startActivity(intent);
    }


    @ReactMethod
    private void publishCarImageUpload(ReadableMap params, Callback callback){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        ArrayList<SCCarPicsModel> carPics = new ArrayList<>();
        if (params.hasKey("carPics")){

           ReadableArray readableArray =  params.getArray("carPics");
            String carPicJson = JSON.toJSONString(readableArray.toArrayList());
            carPics.addAll(JSON.parseArray(carPicJson, SCCarPicsModel.class));
        }

        int index = 0;
        if (params.hasKey("index")){
            index = params.getInt("index");
        }

        Intent intent = new Intent(activity, UploadCarPic.class);
        Bundle bundle = new Bundle();
        bundle.putInt("selectTab",index);
        bundle.putSerializable("carPics",carPics);
        intent.putExtras(bundle);

        activity.startActivity(intent);
    }


    @ReactMethod
    private void selectCarVin(ReadableMap params, Callback callback){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            PermissionDialog dialog = new PermissionDialog(activity,"申请相机拍照权限","申请相机拍照权限，用于拍摄图片识别vin码;");
            dialog.setOnPermissionResultListener(new PermissionDialog.OnPermissionResultListener() {
                @Override
                public void onConfirm() {
                    ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.CAMERA}, 10086);
                }

                @Override
                public void onRefuse() {

                }
            });
            dialog.setCancelable(false);
            dialog.show();


        }else {
            Intent intent = new Intent(activity, QrActivity.class);
            activity.startActivityForResult(intent, MainActivity.REQUEST_FRA_SCANNING);
        }
    }

    @ReactMethod
    private void selectBrand(ReadableMap params, Callback callback){
        System.err.println("isBrandlimit12params" + params);
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }
        int selectLevel = 3;
        if (params.hasKey("selectLevel")){
            selectLevel = params.getInt("selectLevel");
        }
        String from = "";
        if (params.hasKey("from")){
            from = params.getString("from");
        }

        Intent intent = new Intent(activity, SelectBrandsActivity.class);

        if (selectLevel == 3){
            intent.putExtra("isFromAddCar",true);
        }

        // 是否显示品牌的不限
        boolean isBrandLimit = false;
        if (params.hasKey("isBrandLimit")){
            isBrandLimit = params.getBoolean("isBrandLimit");
        }
        intent.putExtra("isBrandLimit",isBrandLimit);

        intent.putExtra("from",from);
        activity.startActivityForResult(intent,MainActivity.REQUEST_SELECT_BRAND);
    }

    /**
     * 上传车辆检测报告
     * @param params
     * @param callback
     */
    @ReactMethod
    private void selectCarDetection(ReadableMap params, Callback callback){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        Intent intent = new Intent(activity, UploadDetectionActivity.class);
        Bundle detectionBundle = new Bundle();
        detectionBundle.putString("detectionReportPic", params.getString("detectionReportPic"));
        detectionBundle.putString("detectionReportUrl", params.getString("detectionReportUrl"));
        detectionBundle.putString("detectionReportPdf", params.getString("detectionReportPdf"));


        intent.putExtras(detectionBundle);

        activity.startActivityForResult(intent,MainActivity.REQUEST_UPLOAD_CHECK_REPORT);
    }

    @ReactMethod
    private void selectContract(ReadableMap params, Callback callback){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        Intent intent = new Intent(activity, UploadContractActivity.class);
        Bundle detectionBundle = new Bundle();
        detectionBundle.putString("contractPic", params.getString("contractPic"));
        detectionBundle.putString("contractPdf", params.getString("contractPdf"));


        intent.putExtras(detectionBundle);

        activity.startActivityForResult(intent,MainActivity.REQUEST_UPLOAD_CONTRACT);
    }

    @ReactMethod
    private void pdfPreview(ReadableMap params){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        String pdfUrl = "";
        if (params.hasKey("pdfUrl")){
            pdfUrl = params.getString("pdfUrl");
        }

        Intent intent = new Intent(activity, PdfPreviewActivity.class);
        intent.putExtra("netUrl",pdfUrl );
        activity.startActivity(intent);
    }

    /**
     * 上传维保报告
     * @param params
     * @param callback
     */
    @ReactMethod
    private void uploadMaintenanceReport(ReadableMap params, Callback callback){
        activity = getCurrentActivity();
        if (activity == null){
            return;
        }

        Intent intent = new Intent(activity, SCMaintenanceReportActivity.class);
        Bundle maintenanceBundle = new Bundle();
        maintenanceBundle.putString("vin", params.getString("vcode"));
        String reportPcUrl = "";
        if (params.hasKey("reportPcUrl")){
            reportPcUrl = params.getString("reportPcUrl");
        }
        String reportPdf = "";
        if (params.hasKey("reportPdf")){
            reportPdf = params.getString("reportPdf");
        }
        String reportPic = "";
        if (params.hasKey("reportPic")){
            reportPic = params.getString("reportPic");
        }
        String carId = "";
        if (params.hasKey("carId")){
            carId = params.getString("carId");
        }
        String page = "";
        if (params.hasKey("page")){
            page = params.getString("page");
        }
        maintenanceBundle.putString("reportPcUrl", reportPcUrl);
        maintenanceBundle.putString("reportPdf", reportPdf);
        maintenanceBundle.putString("reportPic", reportPic);
        maintenanceBundle.putString("carId", carId);
        maintenanceBundle.putString("page", page);
        intent.putExtras(maintenanceBundle);

        activity.startActivityForResult(intent,MainActivity.REQUEST_UPLOAD_CHECK_REPORT);
    }


    @ReactMethod
    public void updateDialog(ReadableMap params) {
        try {
            activity = getCurrentActivity();

            if (activity == null) {
                return;
            }
            int type = 0;
            if (params.hasKey("type")){
                type = params.getInt("type");
            }
            String versionMsg = "";
            if (params.hasKey("versionMsg")){
                versionMsg = params.getString("versionMsg");
            }
            String downloadUrl = "";
            if (params.hasKey("downloadUrl")){
                downloadUrl = params.getString("downloadUrl");
            }

            String finalDownloadUrl = downloadUrl;
            DialogUtil.dialogInfer = new DialogUtil.DialogInfer() {
                @Override
                public void updateClick() {
                    downloadApk(finalDownloadUrl);
                }
            };

            DialogUtil.getUpdateDialog(activity,versionMsg,type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ReactMethod
    public void selectLocalFile(ReadableMap msg){
        activity = getCurrentActivity();
        if (activity == null) {
            return;
        }

        String fileType = "";
        if (msg.hasKey("fileType")){
            fileType = msg.getString("fileType");
        }

        if ("image".equals(fileType)){
            if (ContextCompat.checkSelfPermission(activity,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("申请文件读写存储权限");
                        builder.setMessage("申请文件读写权限，用于选择媒体图片");
                        builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10086);
                            }
                        });
                        builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                });


            }else {

            }
        }else {
            if (ContextCompat.checkSelfPermission(activity,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("申请文件读写存储权限");
                        builder.setMessage("申请文件读写权限，用于选择本地文件上传");
                        builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10086);
                            }
                        });
                        builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                });


            }else {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                activity.startActivityForResult(intent, MainActivity.REQUEST_SELECT_FILE);
            }
        }



    }


    @ReactMethod
    public void selectSelfUser(ReadableMap msg,Callback callback){
        activity = getCurrentActivity();
        if (activity == null) {
            return;
        }

        String title = msg.getString("title");
        String from = msg.getString("from");

        Intent intent = new Intent(activity, SCPurchaserSelectActivity.class);
        intent.putExtra("title",title);
        intent.putExtra("from",from);
        activity.startActivity(intent);

    }

    @ReactMethod
    public void shareToWechatEnt(ReadableMap msg){
        activity = getCurrentActivity();
        if (activity == null) {
            return;
        }

        String title = msg.getString("title");
        String description = msg.getString("description");
        String webpageUrl = msg.getString("webpageUrl");
        String thumbUrl = msg.getString("thumbImage");

        WWMediaLink link = new WWMediaLink();
        link.thumbUrl = thumbUrl;
        link.webpageUrl = URLDecoder.decode(webpageUrl);
        link.title = title;
        link.description = description;
        link.appPkg = SCAppConfig.WWX_PACKAGE;
        link.appName = activity.getString(R.string.app_name);

        link.appId = SCApplication.weworkCorpId;
        link.agentId = SCApplication.weworkAgentId;
        if (SCApplication.getApplication().iwwapi != null)
            SCApplication.getApplication().iwwapi.sendMessage(link, new IWWAPIEventHandler() {
                @Override
                public void handleResp(BaseMessage baseMessage) {
                    Log.e("baseMessage=",baseMessage.toString());
                }
            });

    }

    ProgressDialog progressDialog = null;
    private void downloadApk(String downloadUrl) {

        progressDialog = new ProgressDialog(activity);
        progressDialog.setTitle("更新下载");
        progressDialog.setMessage("正在努力下载");
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();

        File file = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        Log.e("DIRECTORY_DOWNLOADS",file.getAbsolutePath());
        HttpHelper.getInstance().url(downloadUrl)
                .addDownLoadListener(new DownloadListener() {
                    @Override
                    public void onDownloadSuccess(String path, long total) {
                        progressDialog.dismiss();
                        File downloadFile = new File(path);
                        if (downloadFile != null && downloadFile.length() == total) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    installApk(downloadFile);
                                }
                            });

                        } else {
                            downloadFile.delete();
                        }

                    }

                    @Override
                    public void onDownloadSuccess(String path) {

                    }

                    @Override
                    public void onDownloading(int progress) {

                    }

                    @Override
                    public void onDownloadFailed() {

                    }
                })
                .addProgressListener(new ProgressListener() {
                    @Override
                    public void onProgress(long currentBytes, long contentLength, boolean done) {
                        int progress = (int) (currentBytes * 100 / contentLength);
                        progressDialog.setProgress(progress);
                    }
                })
                .addFileName("scyeguan" + ".apk")
                .addSavePath(file.getAbsolutePath() + "/").downloadFile();
    }

    public void installApk(File apkFile) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(activity, "com.shuaiche.yeguan.fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

        } else {
            intent.setDataAndType(
                    Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive");
        }
        activity.startActivity(intent);
    }

    @ReactMethod
    public void checkAudioPermission(Callback callback) {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {

                    if (callback != null) {
                        callback.invoke(true);
                    }
                } else {
                    if (callback != null) {
                        callback.invoke(false);
                    }

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                            builder.setTitle("权限申请");
                            builder.setMessage("获取录音麦克风权限和文件存储权限，录制语音");
                            builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO}, 999);
                                    dialog.dismiss();
                                }
                            });
                            builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.create().show();
                        }
                    });


                }
            } else {
                if (callback != null) {
                    callback.invoke(true);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private MediaRecorder mRecorder;
    private String audioFilePath;
    private MediaPlayer mediaPlayer;



    @ReactMethod
    public void initAudioConfig() {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            try {

                checkAudioRecordPermission(0);

                if (mediaPlayer != null){
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }
    }

    /**
     * 开始录制语音
     */
    @ReactMethod
    public void startAudioRecord() {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            try {

                checkAudioRecordPermission(1);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }
    }

    /**
     * 停止录制语音
     */
    @ReactMethod
    public void stopAudioRecord() {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            try {

                stopRecordAudio();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }
    }

    @ReactMethod
    public void commonEvent(ReadableMap msg) {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            ReadableMapKeySetIterator keyIterator = msg.keySetIterator();
            WritableMap event = Arguments.createMap();
//            String eventName ="";
            while (keyIterator.hasNextKey()) {
                String key = keyIterator.nextKey();
                event.putString(key, msg.getString(key));
//                if(key.equals("eventName")){
//                    eventName=msg.getString(key);
//                }
            }
            sendRCTDeviceEventEmitter(event,"commonEvent");
//            activity.finish();
        }catch (Exception e){

        }
    }

    /**
     * 上传语音
     */
    @ReactMethod
    public void uploadAudio() {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            try {
                HttpHelper.getInstance().appendUrl(HttpUrl.OSS_AUTH)
                        .get(new HttpCallBack<SCAccessAuthResponse>(activity) {
                            @Override
                            public void onSuccessed(SCAccessAuthResponse result) {
                                SCAccessAuthResponse auth = result.getData();

                                String ends = "mp3";

                                MultiImagesUploadManager.MultiImagesUploadCallback callback =
                                        new MultiImagesUploadManager.MultiImagesUploadCallback() {
                                            @Override
                                            public void onSuccess(List<PutObjectRequest> requests) {
                                                if (requests != null) {
                                                    String[] strings = audioFilePath.split("\\/");
                                                    String fileName = strings[strings.length - 1];
                                                    String fileOssPath = "";
                                                    if (requests.size() > 0){
                                                        fileOssPath = SCAppConfig.IM_FILE_URL + requests.get(0).getObjectKey();
                                                    }
                                                    Log.e("fileName",fileName+"");
                                                    Log.e("fileOssPath",fileOssPath+"");
                                                    ReactContext reactContext = getReactApplicationContext();
                                                    if (reactContext == null) {
                                                        return;
                                                    }

                                                    WritableMap event = Arguments.createMap();
                                                    event.putString("url", fileOssPath);
                                                    Log.e("uploadaudio",fileOssPath+"");
                                                    sendRCTDeviceEventEmitter(event,"uploadAudioFinish");
//                                            JSONObject jsonObject = new JSONObject();
//                                            try {
//                                                jsonObject.put("fileName",fileName);
//                                                jsonObject.put("fileOssPath",fileOssPath);
//                                            } catch (JSONException e) {
//                                                e.printStackTrace();
//                                            }
//                                            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("uploadIMSuccess",jsonObject.toString());
                                                }

                                            }

                                            @Override
                                            public void onFailure(List<PutObjectRequest> requests) {
                                                ToastShowUtils.showFailedToast("录音上传失败");
                                                ReactContext reactContext = getReactApplicationContext();
                                                if (reactContext == null) {
                                                    return;
                                                }
                                                reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("uploadIMCancel",null);
                                            }
                                        };

                                new MultiImagesUploadManager().startUploadIMFile(audioFilePath, callback,
                                        auth.getAccessKeyId(), auth.getAccessKeySecret(), auth.getSecurityToken(),
                                        SCAppConfig.OSS_IM_SOUND,ends);
                            }

                            @Override
                            public void onFailured(String errorCode, String errMsg) {
                                ToastShowUtils.showFailedToast(errMsg);
                            }
                        });


            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }
    }

    @ReactMethod
    public void palyLocalAudio() {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            try {

                playAudio(audioFilePath);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }
    }


    @ReactMethod
    public void palyAudio(String url) {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            try {

                playAudio2(url);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }
    }


    @ReactMethod
    public void stopAudio() {
        try {
            activity = getCurrentActivity();
            if (activity == null) {
                return;
            }
            try {

                stopPlayAudio();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }
    }


    private void initConfig() {
        RecordConfig recordConfig = new RecordConfig();
        //采样位宽
        recordConfig.setEncodingConfig(AudioFormat.ENCODING_PCM_16BIT);
        //录音格式
        recordConfig.setFormat(RecordConfig.RecordFormat.MP3);
        //采样频率
        recordConfig.setSampleRate(16000);
//        String recordDir = String.format(Locale.getDefault(), "%s/Record/",
//                Environment.getExternalStorageDirectory().getAbsolutePath());
        //存储目录
        String recordDir = SCApplication.getApplication().getExternalFilesDir(null).getAbsolutePath()+"/";
        recordConfig.setRecordDir(recordDir);
        AudioRecordManager.getInstance().setCurrentConfig(recordConfig);

        AudioRecordManager.getInstance().setStatus(AudioRecordStatus.AUDIO_RECORD_PREPARE);
    }

    private void checkAudioRecordPermission(int type) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
            ) {
                if (type == 0){
                    initConfig();
                }else {
                    startRecordAudio();
                }

            } else {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("权限申请");
                        builder.setMessage("获取录音麦克风权限和文件存储权限，录制语音");
                        builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO}, 999);
                                dialog.dismiss();
                            }
                        });
                        builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                });


            }
        } else {
            if (type == 0){
                initConfig();
            }else {
                startRecordAudio();
            }
        }

    }

    private void playAudio(String filePath) {
        try {
            if (mediaPlayer == null){
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(filePath);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        mediaPlayer.start();
                        Log.e("playOnlineSound", mediaPlayer.getDuration() + "");
                    }
                });
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        sendRCTDeviceEventEmitter(null,"playAudioFinish");
                        if (mp != null) {
                            mp.release();
                        }

                    }
                });
                mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                        Log.e("playOnlineSound", "onError");
                        return false;
                    }
                });
            }else {
                startPlayAudio();
            }




        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    private void playAudio2(String filePath) {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                    Log.e("playOnlineSound", mediaPlayer.getDuration() + "");
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    sendRCTDeviceEventEmitter(null,"playAudioFinish");
                    if (mp != null) {
                        mp.release();
                    }

                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    Log.e("playOnlineSound", "onError");
                    return false;
                }
            });


        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    private void stopPlayAudio(){
        if (mediaPlayer != null){
            mediaPlayer.pause();
        }
    }

    private void startPlayAudio(){
        if (mediaPlayer != null){
            mediaPlayer.start();
        }
    }

    private void startRecordAudio() {
        AudioRecordManager.getInstance().setRecordStateListener(new RecordStateListener() {
            @Override
            public void onStateChange(AudioRecordStatus state) {

            }

            @Override
            public void onError(String error) {

            }
        });

        AudioRecordManager.getInstance().setRecordResultListener(new RecordResultListener() {
            @Override
            public void onResult(File result) {
                Log.e("onResult",result.getAbsolutePath());
                audioFilePath = result.getAbsolutePath();
            }
        });
        AudioRecordManager.getInstance().setStatus(AudioRecordStatus.AUDIO_RECORD_START);

    }

    private void stopRecordAudio() {
        Log.e("stopRecordAudio","stopRecordAudio");
        AudioRecordManager.getInstance().setStatus(AudioRecordStatus.AUDIO_RECORD_STOP);
    }

    private void sendRCTDeviceEventEmitter(WritableMap event, String eventName) {

        try {
            ReactContext reactContext = getReactApplicationContext();
            if (reactContext == null) {
                return;
            }
            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, event);
        } catch (Exception e) {

        }
    }


}
